package br.edu.ufcg.lsd.wbis;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

import br.edu.ufcg.lsd.wbis.control.WBISController;
import br.edu.ufcg.lsd.wbis.control.exception.CannotOpenDatabaseSessionException;
import br.edu.ufcg.lsd.wbis.control.exception.WBISException;


public class ErrorInvocationHandler implements InvocationHandler {

	private final WBISController controller;

	public ErrorInvocationHandler() throws CannotOpenDatabaseSessionException {
		this.controller = new WBISController();
	}

	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		try {
			return method.invoke(this.controller, args);
		} catch (Throwable e) {
			Class<?> clazz = e.getClass();
			if (clazz.equals(InvocationTargetException.class)) {
				clazz = e.getCause().getClass();
			}
			if (Arrays.asList(method.getExceptionTypes()).contains(clazz)) {
				WBISException exception = (WBISException) clazz.getConstructor().newInstance();
				exception.setMessage(clazz.getSimpleName());
				throw exception;
			}
			throw new RuntimeException("Unexpected error!", e);
		}
	}
}
